<template>
  <el-form ref="ruleFormRef" :rules="rules" :model="banner" class="form-box" >

    <el-form-item prop="img">
      <el-input v-model="banner.img" placeholder="图片地址" />
    </el-form-item>
    <el-form-item prop="link">
      <el-input v-model="banner.link" placeholder="图片跳转连接" />
    </el-form-item>
    <el-form-item>
      <el-input v-model="banner.alt" placeholder="图片提示" />
    </el-form-item>
    <el-form-item>
      <el-switch v-model="banner.flag"></el-switch>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="addBanner(ruleFormRef)">添加</el-button>
      <el-button>取消</el-button>
    </el-form-item>

  </el-form>

</template>

<script setup lang="ts">

import type { IBanner } from "@/myTypes";
import { reactive, ref } from "@vue/reactivity";
import { addBannerApi } from "@/api/banners.ts"
import type { AxiosResponse } from "axios";
import type { FormInstance, FormRules } from 'element-plus'
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const ruleFormRef = ref<FormInstance>();

// 定义轮播图的数据
const banner = reactive<IBanner>({
  "bannerid": "",
  "img": "",
  "link": "",
  "alt": "",
  "flag": true
})

const router = useRouter();

// 添加轮播图
function addBanner(formEl: FormInstance | undefined) {

  if (!formEl) return;

  // 验证表单元素的内容是否符合规则。
  formEl.validate((valid) => {
    if (valid) {
      // 添加轮播图
      addBannerApi(banner)
        .then((res: AxiosResponse) => {
          if (res.data.code === "200") {
            ElMessage({
              type:"success",
              message:"添加成功！",
              duration:1000,
              onClose:function(){
                router.push("/Admin/BannerList");
              }
            })

          }
        })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

function validateImg(rule: any, value: any, callback: any) {
  if (!(/^https:\/\//.test(value))) {
    callback(new Error('图片地址应该以https://开头'));
  } else {
    callback();
  }
}




// 表单验证
const rules = reactive<FormRules>({
  img: [
    { required: true, message: 'Please input 图片地址', trigger: 'blur' },
    { min: 15, max: 200, message: '图片地址长度在15到200位之间', trigger: 'blur' },
    {
      validator: validateImg, trigger: 'blur'
    }
  ],
  link: [
    { required: true, message: 'Please input 图片的跳转连接', trigger: 'blur' }

  ]
})

</script>

<style>

</style>